# -*- coding: utf-8 -*-
#   网络方面的函数
# @Time    ： 2024/4/7  23:39
# @Auther  ： 徐良
# File     :  networkFunction.py
import socket

import pytz
import datetime
from PySide6.QtCore import QUrl, QCoreApplication
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest


# ************************************      日期和时间函数            ***********************************
def getStandardDate():
    """获取当前标准日期的字符串"""
    sDate = getStandardTime()
    return sDate[0:10]


def getStandardTime():

    tz = pytz.timezone('Asia/Shanghai')
    now = datetime.datetime.now(tz)
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


def getHostname():
    """获取本机名"""
    hostname = socket.gethostname()
    return hostname


def check_network(url):
    """
    检查网络是否通
    :param url:
    :return:
    """
    app = QCoreApplication.instance()
    if app is None:
        app = QCoreApplication([])

    manager = QNetworkAccessManager()
    request = QNetworkRequest(QUrl(url))

    # 创建一个等待请求完成的标志
    finished = False

    def handle_finished():
        nonlocal finished
        finished = True
        app.quit()

    # 连接请求完成的信号
    manager.finished.connect(handle_finished)

    # 发送请求
    manager.get(request)

    # 开启事件循环
    app.exec()

    # 根据请求完成状态来返回结果
    return finished


def getIpaddress(hname):
    """获取本机地址"""
    ip_address = socket.gethostbyname(hname)
    return ip_address
